package com.yhj.reggie.controller;

import com.yhj.reggie.common.R;
import com.yhj.reggie.entity.Employee;
import com.yhj.reggie.entity.Page;
import com.yhj.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;
    @PostMapping ("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpSession session){

        R<Employee> employeeR = employeeService.login(employee);

        if (employeeR.getCode() == 1){
            session.setAttribute("employee",employeeR.getData().getId());
        }

        return employeeR;
    }

    @PostMapping("/logout")
    public R<String> logout(HttpSession session){
        session.invalidate();
        return R.success("退出成功");
    }
    @PostMapping
    public R<String> save(@RequestBody Employee employee,HttpSession session) {
        Long id = (Long) session.getAttribute("employee");

        employee.setCreateUser(id);
        employee.setUpdateUser(id);

        employeeService.save(employee);
        return R.success("添加成功");
    }
    @RequestMapping("/page")
    public R<Page<Employee>> findPage(Integer page, Integer pageSize,String name){
        Page<Employee> pageShow = employeeService.findByPage(page, pageSize, name);
        return R.success(pageShow);
    }
    @PutMapping
    public R<String> update(@RequestBody Employee employee,HttpSession session){
        Long id = (Long)session.getAttribute("employee");
        employee.setUpdateUser(id);
        employeeService.update(employee);
        return R.success("修改成功");
    }
    //回显
    @GetMapping("/{id}")
    public R<Employee> findById (@PathVariable Long id){
        R<Employee> byId = employeeService.findById(id);
        byId.setMsg("回显成功");
        return byId;
    }



}
